package at.rtm.web;

import at.rtm.dao.HRDTemperatureDAOImpl;
import at.rtm.domain.Temperature;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * The main controller displays all temperatures collected.
 */
@Controller
public class MainController {
    @Autowired
    HRDTemperatureDAOImpl temperatureDataDAO;

    @RequestMapping(value = "index.html")
    public String handleRequest(HttpServletRequest req, Model model) {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        if (user == null) {
            return "redirect:" + userService.createLoginURL(req.getRequestURI());
        }


        List<Temperature> temperatures = temperatureDataDAO.findAll();
        String currenttemperatureMessage = "n/a";
        if (!temperatures.isEmpty()) {
            currenttemperatureMessage = temperatures.get(0).getTemperature().toString();
        }
        model.addAttribute("user", user);
        model.addAttribute("temperatures", temperatures);
        model.addAttribute("currenttemperature", currenttemperatureMessage);
        return "index";

    }

}
